package com.mall.user.services;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.mall.user.IRegisterService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.UserRegisterRequest;
import com.mall.user.dto.UserRegisterResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * @author wangdezhao
 * @date 2021/6/18
 * @description
 */
@Service
@Slf4j
@Transactional
public class RegisterServiceImpl implements IRegisterService {

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    UserVerifyMapper userVerifyMapper;

    @Autowired
    JavaMailSender javaMailSender;

    @Override
    public UserRegisterResponse register(UserRegisterRequest request) {
        UserRegisterResponse registerResponse = new UserRegisterResponse();
        request.requestCheck();


        if (IsNameRepeat(request)){   // 判断是否重复名称
            registerResponse.setCode(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode());
            registerResponse.setMsg(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
            return registerResponse;
        }

        //    2. 插入member表
        Member member = new Member();

        member.setCreated(new Date());
        member.setUpdated(new Date());
        member.setIsVerified("N");
        member.setState(1);
        member.setEmail(request.getEmail());
        member.setUsername(request.getUserName());
        member.setPassword(SecureUtil.md5(request.getUserPwd())); // 对密码进行md5加密
        int effectRow1 = memberMapper.insert(member);// 插入数据
        if (effectRow1!= 1){
            registerResponse.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
            registerResponse.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
            return registerResponse;
        }

        //    3. 插入verify表
        UserVerify userVerify = new UserVerify();

        userVerify.setIsExpire("N");
        userVerify.setIsVerify("N");
        userVerify.setRegisterDate(new Date());
        userVerify.setUsername(request.getUserName());
        String uuid = IdUtil.randomUUID();
        userVerify.setUuid(uuid); // 生成随机uuid
        int effectRow2 = userVerifyMapper.insert(userVerify);
        if (effectRow2!= 1){
            registerResponse.setCode(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getCode());
            registerResponse.setMsg(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getMessage());
            return registerResponse;
        }

        //    4. 发送邮件
        sendEmail(uuid,request);

        //    5. 打印日志
        log.info("注册成功,用户信息: {} ", JSONUtil.toJsonStr(request));
        registerResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
        registerResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return registerResponse;
    }

    private void sendEmail(String uuid, UserRegisterRequest request) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("wdz18801406178@163.com");
        message.setTo(request.getEmail());
        message.setSubject("mail api test");
        String userName = request.getUserName();
        message.setText("http://localhost:8080/user/verify?uid="+uuid+"&username="+ userName);
        javaMailSender.send(message);
        log.info("邮件发送成功: \n邮箱: {} \nuuid: {}",request.getEmail(),uuid);

//        hutools
//        MailAccount account = new MailAccount();
//        account.setHost("smtp.163.com");
//        account.setPort(25);
//        account.setAuth(true);
//        account.setFrom("wdz18801406178@163.com");
//        account.setUser("keendy");
//        account.setPass("BHCZUCIFGJCIUNLE");
//        MailUtil.send(account, CollUtil.newArrayList(request.getEmail()), "激活邮件", "http://localhost:8080/user/verify?uuid="+uuid,false);
    }

    private boolean IsNameRepeat(UserRegisterRequest request) {
        Example example = new Example(Member.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", request.getUserName());
        List<Member> members = memberMapper.selectByExample(example);// 查出member对象
        if (members.size() == 0){
            return false;
        }
        return true;
    }
}
